package com.kichina.parking.upstream;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kichina.parking.exception.extend.JsonParseException;
import com.kichina.parking.service.logic.bean.OperatorInfoRecord;
import com.kichina.parking.service.logic.service.OperatorInfoRecordService;
import com.kichina.parking.utils.JsonToEntityUtil;
import com.kichina.parking.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * @author Surging
 * @version 1.0
 * @ClassName MonthPayUpstreamHandler
 * @date 2022-09-14 20:03
 * @desc 车场首次启用或操作员变化后上传操作员信息业务处理层
 */
@Component
@Slf4j
public class Parking6OperatorInfoUpstreamHandler {

    private final OperatorInfoRecordService operatorInfoRecordService;

    public Parking6OperatorInfoUpstreamHandler(OperatorInfoRecordService operatorInfoRecordService) {
        this.operatorInfoRecordService = operatorInfoRecordService;
    }

    /**
     * @param jsonObject 数据实体
     * @author Surging
     * @Description 车场首次启用或操作员变化后上传操作员信息业务处理层
     * (操作员ID ，operate_id 为唯一值，如平台有对应值，请更新操作员相关信息)
     * @Return void
     * @date 20:53 2022-09-15
     **/
    public void recordParkingOperatorInfoUpstream(JSONObject jsonObject) throws JsonParseException {

        OperatorInfoRecord operatorInfoRecord;
        try {
            operatorInfoRecord = JsonToEntityUtil.jsonToEntity(jsonObject, OperatorInfoRecord.class);
            LambdaQueryWrapper<OperatorInfoRecord> eq = new QueryWrapper<OperatorInfoRecord>().lambda()
                    .eq(OperatorInfoRecord::getParkid, operatorInfoRecord.getParkid())
                    .eq(OperatorInfoRecord::getOperateId, operatorInfoRecord.getOperateId());
            List<OperatorInfoRecord> operatorInfoRecords = operatorInfoRecordService.list(eq);
            if (CollectionUtils.isNotEmpty(operatorInfoRecords)){
                //更新
                operatorInfoRecord.setUpdateTime(new Date());
                operatorInfoRecordService.update(operatorInfoRecord, eq);
            }else {
                //添加
                operatorInfoRecord.setOperatorInfoRecordId(UUIDUtil.getUUID());
                operatorInfoRecord.setUpdateTime(new Date());
                //原实体有createTime字段，serviceCreateTime作区分
                operatorInfoRecord.setServiceCreateTime(new Date());
                operatorInfoRecordService.save(operatorInfoRecord);
            }
        } catch (ParseException e) {
            log.error("数据格式不合法，解析失败");
            throw new JsonParseException("数据格式不合法，解析失败");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
